package com.ujs.leetcode.FourSum;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zhangshihao
 * @create 2023-10-17 20:36
 */
public class Solution {
    public static void main(String[] args) {
        int[] nums = new int[]{1, 0, -1, 0, -2, 2};
        int target = 0;
        List<List<Integer>> lists = fourSum(nums, target);
        System.out.println(lists);
    }

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        sort(nums, 0, nums.length - 1);
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0 && nums[i] > target) {
                return result;
            }
            if (i > 0 && nums[i - 1] == nums[i]) { // 去重
                continue;
            }
            for (int j = 0; j < nums.length; j++) {
                if (j > i + 1 && nums[j - 1] == nums[j]) {
                    continue;
                }
                int left = j + 1;
                int right = nums.length - 1;
                while (right > left) {
                    long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) {
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        // 对nums[left]和nums[right]去重
                        while (right > left && nums[right] == nums[right - 1]) right--;
                        while (right > left && nums[left] == nums[left + 1]) left++;
                        left++;
                        right--;
                    }
                }
            }
        }
        return result;
    }

    public static void sort(int[] nums, int begin, int end) {
        if (begin > end) {
            return;
        }
        int k = nums[begin], i = begin, j = end;
        while (i != j) {
            while (nums[j] >= k && i < j) {
                j--;
            }
            while (nums[i] <= k && i < j) {
                i++;
            }
            if (i < j) {
                int temp = nums[i];
                nums[j] = nums[i];
                nums[i] = temp;
            }
            if (i == j) {
                break;
            }
        }
        nums[begin] = nums[i];
        nums[i] = k;
        sort(nums, begin, i - 1);
        sort(nums, i + 1, end);
    }
}
